﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.IO;
using System.Net.NetworkInformation;
using QLibrary.Helper;
using QModel;

namespace QLibrary.Engine
{
    public class HttpEngine
    {
        #region Fields
        private HttpWebRequest _httpWebRequest;
        #endregion

        #region Handler
        public event EventHandler<FetchCompletedEventArgs> FetchDataCompleted;
        #endregion

        #region Properties
        public CommonReqEntity ReqEntity { get; set; }
        public Dictionary<string, object> ResultData { get; set; }
        public QParser Parser { get; set; }
        #endregion

        #region Constructor
        public HttpEngine(CommonReqEntity reqEntity, QParser parser, Dictionary<string, object> resultData)
        {
            this.ReqEntity = reqEntity;
            this.Parser = parser;
            this.ResultData = resultData;
        }
        #endregion

        #region Method
        public int FetchData()
        {
            if (!NetworkInterface.GetIsNetworkAvailable())
            {
                return -1;
            }
            if (HttpMethod.POST == ReqEntity.ReqMethod)
            {
                _httpWebRequest = (HttpWebRequest)WebRequest.Create(ReqEntity.Url);
                AddHeader();
                _httpWebRequest.Method = ReqEntity.ReqMethod.ToString();
                _httpWebRequest.ContentType = "application/x-www-form-urlencoded";
                _httpWebRequest.BeginGetRequestStream(new AsyncCallback(RequestCallback), _httpWebRequest);
            }
            if (HttpMethod.GET == ReqEntity.ReqMethod)
            {
                _httpWebRequest = (HttpWebRequest)WebRequest.Create(ReqEntity.Url + "?" + ParamHelper.BuildParas(ReqEntity.Body));
                AddHeader();
                _httpWebRequest.Method = ReqEntity.ReqMethod.ToString();
                this._httpWebRequest.BeginGetResponse(new AsyncCallback(ResponseCallback), _httpWebRequest);
            }
            return 0;
        }
        /// <summary>
        /// 添加头信息
        /// </summary>
        private void AddHeader()
        {
            //TODO 添加头信息
        }

        public void CancelFetch()
        {
            if (_httpWebRequest != null)
            {
                FetchDataCompleted = null;
                _httpWebRequest.Abort();
            }
        }
        #endregion

        #region Callback
        public void RequestCallback(IAsyncResult result)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)result.AsyncState as HttpWebRequest;
                StreamWriter streamWriter = new StreamWriter(request.EndGetRequestStream(result));
                streamWriter.Write(ParamHelper.BuildParas(ReqEntity.Body));
                streamWriter.Flush();
                streamWriter.Close();
                request.BeginGetResponse(new AsyncCallback(ResponseCallback), request);
            }
            catch (Exception ex)
            {
                if (ResultData.ContainsKey("ErrorEntity"))
                {
                    ErrorEntity errorEntity = ResultData["ErrorEntity"] as ErrorEntity;
                    errorEntity.ErrorMessage = ex.Message.ToString();
                    errorEntity.ErrorStackTrace = ex.StackTrace.ToString();
                    if (FetchDataCompleted != null)
                    {
                        FetchDataCompleted(this, new FetchCompletedEventArgs(ResultData, ErrorType.Err_WebException));
                    }
                }
            }
        }

        public void ResponseCallback(IAsyncResult result)
        {
            try
            {
                HttpWebRequest request = result.AsyncState as HttpWebRequest;
                WebResponse response = request.EndGetResponse(result);
                using (Stream responseStream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(responseStream))
                    {
                        string jsonData = reader.ReadToEnd();//返回的结果
                        Parser.ParseJson(jsonData, ResultData);
                        if (FetchDataCompleted != null)
                        {
                            FetchDataCompleted(this,new FetchCompletedEventArgs(ResultData, ErrorType.Err_Null));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (ResultData.ContainsKey("ErrorEntity"))
                {
                    ErrorEntity errorEntity = ResultData["ErrorEntity"] as ErrorEntity;
                    errorEntity.ErrorMessage = ex.Message.ToString();
                    errorEntity.ErrorStackTrace = ex.StackTrace.ToString();
                    if (FetchDataCompleted != null)
                    {
                        FetchDataCompleted(this, new FetchCompletedEventArgs(ResultData, ErrorType.Err_WebException));
                    }
                }
            }
        }
        
        #endregion
    }
}
